import {
    createRouter,
    createWebHashHistory,
    createWebHistory,
} from "vue-router";
import type { RouterOptions, RouteRecordRaw } from "vue-router";
import Cookies from "js-cookie";
import user from "../store/user/user";
import { getAdminInfoAPI } from "../request/api";
import store from "../store";
const route: RouterOptions = {
    // history:createWebHashHistory(),
    history: createWebHistory(),

    routes: [
        // {
        //     path: "/",
        //     redirect: "/login",
        // },
        {
            path: "/login",
            component: () => import("../pages/Login/Login.vue"),
        },
        // {
        //     path: "/home",
        //     component: () => import("../pages/Home/Home.vue"),
        // },
    ],
};

const router = createRouter(route);

/* 
    next 方法有参数,它代表会下一次会在进入前置导航守卫
*/
router.beforeEach(async (to, from, next) => {
    const token = Cookies.get("token");

    type StateType = typeof store.state;
    type Usertype = StateType & { user: StateType };

    let premission = (store.state as Usertype).user.premission;

    if (token && premission.length === 0) {
        // 获取用户信息
        let adminInfo = await getAdminInfoAPI();
        
        //  存储用户信息
        store.commit("user/upDatePre", adminInfo.data.menus);
        store.commit("user/username", adminInfo.data.username);

        // 获取 user/genMenus 数据
        const genMenus = store.getters["user/genMenus"];
        
        //动态生成路由记录
        for (const key in genMenus) {
            let routesObj: RouteRecordRaw = {
                path: "/" + genMenus[key].name,
                name: genMenus[key].title,
                component: () => import("../pages/Home/Home.vue"),
                children: [],
            };
            for (let i = 0; i < genMenus[key].submenus.length; i++) {
                let obj = {
                    path: genMenus[key].submenus[i].name,
                    name: genMenus[key].submenus[i].title,
                    component: () =>
                        import(
                            `../pages/${genMenus[key].name}/${genMenus[key].submenus[i].name}.vue`
                        ),
                };
                routesObj.children?.push(obj);
            }
            // 添加路由
            router.addRoute(routesObj);
        }
        router.addRoute({
            path: "/",
            component: () => import("../pages/Home/Home.vue"),
            children: [
                {
                    path: "index",
                    component: () => import("../pages/index/index.vue"),
                },
            ],
        });
        next(to);
    } else if (!token && to.path !== "/login") {
        next('/login')
    } else if (token && to.path === "/login") {
        next(from)
    } else {
        next();
    }
});

export default router;
